package com.feng.d16openclosedprinciple.goodsmell;

import com.feng.d16openclosedprinciple.badsmell.AlertRule;
import com.feng.d16openclosedprinciple.badsmell.Notification;

/**
 * 单例模式创建Alert的工厂类
 * @author LiYilin on 2020/4/11
 */
public class ApplicationContext {
    private AlertRule alertRule;
    private Notification notification;
    private Alert alert;

    /**
     * 这里是扩展点,如果想要添加新的报警规则.只需要创建新的AbstractAlertHandler子类,
     * 然后在这里初始化alert的时候添加进去就可以了,不需要再改动其他的地方,
     * 单元测试也只需要保证新添加的AbstractAlertHandler子类逻辑正确即可.老的单元测试都不会失败,也不用修改
     */
    public void init() {
        //为了演示,使用的空参构造,实际情况应该做一些初始化的操作
        alertRule = new AlertRule();
        notification = new Notification();
        alert = new Alert();
        alert.addApiStateInfo(new TpsAlertHandler(alertRule, notification));
        alert.addApiStateInfo(new ErrorAlertHandler(alertRule, notification));
    }

    /**
     * 饿汉式单例
     */
    private static final ApplicationContext instance = new ApplicationContext();
    private ApplicationContext() {
        instance.init();
    }

    public static ApplicationContext getInstance() {
        return instance;
    }

    private Alert getAlert() {
        return alert;
    }

    public static void main(String[] args) {
        ApiStatInfo apiStatInfo = new ApiStatInfo();
        //省略设置apiStatInfo数据
        ApplicationContext.getInstance().getAlert().check(apiStatInfo);
    }
}
